package db;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import db.*;

public class ListUsers extends HttpServlet {

//doPost method included for POST requests
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        doGet(request, response);
    }

//This subroutine is called from SubmitQ.jsp
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		DatabaseConnector DBConnect = new DatabaseConnector(DatabaseConnector.getDatabaseType());

		String SQL = "select U.username, U.password, I.email from Users U, User_Info I "+
			                "where U.username=I.username ORDER BY username";

	    String[][] rs = DBConnect.selectSQL(SQL,3);

	    out.println("<html><head>");

	    out.println("<script type=\"text/javascript\">");
	    out.println("function message(username){");
		out.println("var ans = confirm(\"Are you sure you want to delete user '\"+username+\"'?\");");
		out.println("if (ans==true){");
	    out.println("document.location.href = \"DelUser?username=\"+username;");
		out.println("} }");
	    out.println("</script>");

	    out.println("</head><body>");

		out.println("<table border=\"1\" cellpadding=\"3\">");
		out.print("<tr><td bgcolor=\"c0c0c0\">Username</td>");
		out.print("<td bgcolor=\"c0c0c0\">Password</td>");
		out.println("<td bgcolor=\"c0c0c0\">E-mail</td>");
		out.println("<td bgcolor=\"c0c0c0\">Control</td></tr>");

		try{
			for(int i=0;i<rs.length;i++) {
				out.print("<tr>");
				for(int j=0;j<rs[i].length;j++){
					out.print("<td>" + rs[i][j] + "</td>"); }
				out.print("<td><form method=\"post\" action=\"addUser\" style=\"margin: 0px; display:inline;\">");
				out.println("<input type=\"hidden\" name=\"username\" value=\""+rs[i][0]+"\" />");
				out.println("<input type=\"submit\" value=\"Edit\" onclick=\"this.form.action='EditUser?username="+rs[i][0]+"&loadCase=edit'\" /></form>");
				out.println("<input type=\"submit\" value=\"Delete\" onclick=\"message('" + rs[i][0] + "')\" /></td></tr>");
			}
		} catch (NullPointerException npe){
			//no data in the tables
		}
		out.println("</table>");

        out.print("<form method=\"post\" action=\"AddUser?loadCase=add\" style=\"margin: 0px; display:inline;\">");
        out.println("<input type=\"submit\" value=\"Add New User\" /></form>");

	    out.println("</body></html>");
    }
}

